

package com.hazelcast.internal.server.tcp;

import com.hazelcast.instance.ProtocolType;
import com.hazelcast.internal.networking.InboundHandler;
import com.hazelcast.internal.nio.ascii.MemcacheTextDecoder;
import com.hazelcast.internal.nio.ascii.RestApiTextDecoder;

import java.nio.ByteBuffer;

public class TextHandshakeDecoder extends SingleProtocolDecoder {

    public TextHandshakeDecoder(ProtocolType supportedProtocol, InboundHandler next, SingleProtocolEncoder encoder) {
        super(supportedProtocol, next, encoder);
    }

    @Override
    protected boolean verifyProtocol(String incomingProtocol) {
        super.verifyProtocolCalled = true;
        handleUnexpectedProtocol(incomingProtocol);
        if (ProtocolType.REST == supportedProtocol) {
            if (!RestApiTextDecoder.TEXT_PARSERS.isCommandPrefix(incomingProtocol)) {
                encoder.signalWrongProtocol("Unsupported protocol exchange detected, expected protocol: REST" + ", actual protocol or first three bytes are: " + incomingProtocol);
                return false;
            }
        } else {
            if (!MemcacheTextDecoder.TEXT_PARSERS.isCommandPrefix(incomingProtocol)) {
                encoder.signalWrongProtocol("Unsupported protocol exchange detected, expected protocol: MEMCACHED" + ", actual protocol or first three bytes are: " + incomingProtocol);
                return false;
            }
        }
        return true;
    }

    @Override
    protected void setupNextDecoder() {
        super.setupNextDecoder();
        // we need to restore whatever is read
        ByteBuffer src = this.src;
        ByteBuffer dst = (ByteBuffer) inboundHandlers[0].src();
        src.flip();
        dst.put(src);
    }
}
